import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter{
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化操作
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false);

        // 获取请求的URI
        String requestURI = httpRequest.getRequestURI();

        // 如果访问的是success.jsp，检查用户是否已经登录
        if (requestURI.endsWith("success.jsp")) {
            boolean isLoggedIn = (session != null && session.getAttribute("username") != null);

            // 如果用户已登录或者访问登录页面，则放行
            if (isLoggedIn || requestURI.endsWith("servletControll")) {
                chain.doFilter(request, response);
            } else {
                // 否则，重定向到登录页面
                httpResponse.sendRedirect("login.jsp");
            }
        } else {
            // 对于其他 JSP 页面，直接放行
            chain.doFilter(request, response);
        }
    }


    public void destroy() {
        // 销毁操作
    }
}
